// pages/function_test/directory_browse/index.ts

import { RCSPOpDirectoryBrowse } from "../../../lib/rcsp-impl/rcsp";
import { OPDirectoryBrowse } from "../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
var currentFile: OPDirectoryBrowse.File
Page({

    /**
     * 页面的初始数据
     */
    data: {
        listFile: new Array<OPDirectoryBrowse.File>(),
        isEnd: false,
        pathFile: new Array<String>(),
        pathScrollX: 100,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(_option) {
        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            const file = data.data as OPDirectoryBrowse.File | undefined
            if (file) {
                RCSPOpDirectoryBrowse?.appendBrowse(file).then(_devFolder => {
                    const rootFolder = _devFolder.listFile()?.[0]
                    if (rootFolder) {
                        currentFile = rootFolder
                        RCSPOpDirectoryBrowse?.appendBrowse(rootFolder).then(_rootFolder => {
                            this._handleFileList(_rootFolder)
                        })
                    }
                })
            }
        })
    },
    //点击文件路径切换
    clickPath(e: any) {
        console.log("e : ", e);
        const index = e.currentTarget.dataset.index
        let targetPath = ""
        for (let i = 0; i <= index; i++) {
            const element = this.data.pathFile[i];
            if (i == 0) {
                targetPath += element
            } else {
                targetPath += "/" + element
            }
        }
        console.log("targetPath " + targetPath);

        const file = RCSPOpDirectoryBrowse?.getFileByPath(targetPath)
        if (file) {
            RCSPOpDirectoryBrowse?.appendBrowse(file).then(_folder => {
                this._handleFileList(_folder)
            })
        } else {
            console.log("file 不存在");
        }
    },
    //点击文件夹浏览
    clickDirectoryBrowse(e: any) {
        console.log("e : ", e);
        const index = e.currentTarget.dataset.index
        const file = this.data.listFile[index]
        console.log("file : ", file);
        if (file.isDirectory()) {
            RCSPOpDirectoryBrowse?.appendBrowse(file).then(_folder => {
                this._handleFileList(_folder)
            }).catch((error) => {
                wx.showToast({ title: error, icon: "none" })
            })
        } else {
            wx.showToast({ title: "请长按文件进行操作", icon: "none" })
        }
    },
    //加载更多
    loadMore(e: any) {
        console.log("加载更多", e);
        RCSPOpDirectoryBrowse?.loadMore(currentFile).then(_folder => {
            this._handleFileList(_folder)
        })
    },
    _handleFileList(_folder: OPDirectoryBrowse.File) {
        const parents = _folder.path.split("/")
        currentFile = _folder
        const tempList = _folder.listFile()
        const result = new Array<OPDirectoryBrowse.File>()
        tempList?.forEach(element => {
            //@ts-ignore
            element.name = element.getName()
            //@ts-ignore
            element.isDirectoryFile = element.isDirectory()
            result.push(element)
        });
        console.log(" folder.list ", _folder.list());
        this.setData({ listFile: result, isEnd: _folder.isLoadFinished(), pathFile: parents })
    },
    //文件操作-长按
    operateFile(e: any) {
        const item: OPDirectoryBrowse.File = this.data.listFile[e.currentTarget.dataset.index]
        console.log("item", item);
        if (item.isDirectory()) {
            return
        }
        const that = this
        return wx.showActionSheet({
            alertText: item.getName(),
            itemList: ["删除", "读取文件"],
            success(res) {
                switch (res.tapIndex) {
                    case 0://删除
                        RCSPOpDirectoryBrowse?.deleteFile([item]).then(() => {
                            that._handleFileList(currentFile)
                            wx.showToast({ title: "删除成功" })
                        }).catch(() => {
                            wx.showToast({ title: "删除失败" })
                        })
                        break;
                    case 1://读文件
                        wx.navigateTo({
                            url: "../large_file_get/index?pagetype=0",
                            success: (res) => {
                                res.eventChannel.emit('acceptDataFromOpenerPage', { fileName: item.getName(), cluster: item.getCluster(), devIndex: item.getDevIndex() })
                            }
                        })
                        // if (RCSPOpLargeFileGet?.isFree() == true) {
                        //     let sdCardBean: OPFile.SDCardBean | undefined
                        //     const storageDevs = RCSPOpFile?.getOnLineSdCardBeans()
                        //     if (storageDevs) {
                        //         for (let index = 0; index < storageDevs.length; index++) {
                        //             const element = storageDevs[index];
                        //             const devIndex = element.devHandler
                        //             if (devIndex == item.getDevIndex()) {
                        //                 sdCardBean = element
                        //                 break
                        //             }
                        //         }
                        //     }
                        //     const fileName = item.getName()
                        //     if (sdCardBean && fileName) {
                        //         const getFileCallback: OPLargerFileGet.TransferTaskCallback = {
                        //             onError: (code: number) => {
                        //                 console.error("读文件失败，error code : " + code);
                        //             },
                        //             onStart: () => {
                        //                 console.log("开始读文件");
                        //             },
                        //             onProgress: (progress: number, packectData?: ArrayBuffer) => {
                        //                 console.log("读文件 进度" + progress + " , data size " + packectData?.byteLength);
                        //             },
                        //             onSuccess: (data: ArrayBuffer) => {
                        //                 console.log("读文件成功，" + ab2hex(data));
                        //                 wx.saveFileToDisk
                        //             },
                        //             /**
                        //              * @param code
                        //              * 0:主动取消
                        //              * 1:丢包
                        //              * 2：crc错误
                        //             */
                        //             onCancel: (reason: number) => {
                        //                 console.error("读文件取消，reason ：" + reason);
                        //             }
                        //         }
                        //         RCSPOpLargeFileGet.excuteGetTaskByFileNameAndDevHandle({
                        //             offset: 0,
                        //             sdCardBean: sdCardBean,
                        //             fileName: fileName,
                        //             callback: getFileCallback
                        //         })
                        //     }
                        // }
                        break;
                    default:
                        break;
                }

                // const file = storageDevs[res.tapIndex]
                // wx.navigateTo({
                //     url: '/pages/function_test/directory_browse/index',
                //     success: function (res) {
                //         // 通过eventChannel向被打开页面传送数据
                //         res.eventChannel.emit('acceptDataFromOpenerPage', { data: file })
                //     }
                // })
            }
        })
    },
    backBrowse(_e: any) {
        RCSPOpDirectoryBrowse?.backBrowse(currentFile).then(_folder => {
            this._handleFileList(_folder)
        })
    },
    reloadFolder() {
        RCSPOpDirectoryBrowse?.reloadFolder(currentFile).then(_folder => {
            this._handleFileList(_folder)
        })
    }
})